<template>
  <div class="addressBox" ref="addressBox">
    <v-header-title :title="title"></v-header-title>
    <div class="address">
      <div class="add-address" @click="goAddAddress">
        <mt-cell title="新增收获地址" is-link>
          <span class="icon-add"></span>
        </mt-cell>
      </div>
      <div class="address-wrapper">
        <ul>
          <li v-for="(item, index) in addressList" :key="item.id" class="address-list" :class="{disable:item.disable}">
            <div class="list-content">
              <div class="icon-select" v-show="item.isDefault=='YES'"></div>
              <div class="address-info" @click="selectAddress(item)" :addressId="item.id">
                <p class="address-detail">{{item.detail}}</p>
                <span class="user-name">{{item.username}}</span>
                <span class="mobile">{{item.mobile}}</span>
              </div>
              <span class="icon-modify" @click="editAddress(item)"></span>
              <span class="icon-delete" @click="deleteAddress(item)"></span>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue';
  import BScroll from 'better-scroll';
  import {MessageBox} from 'mint-ui';
  import headerWithTitle from 'components/header/HeaderWithTitle';
  import {setSessionStorageItem, getSessionStorageItem} from 'components/api/utils';
  import {getUserShippingAddressList, deleteUserShippingAddress} from 'components/api/interface-hhy';
  import {getBusinessSetting} from 'components/api/interface-saas';
  import {DEFALUT_ADDRESS} from 'components/api/index-web';
  export default {
    data() {
      return {
        userShippingAddressList: Object,
        title: '选择配送地址',
        currentIndex: 0,
        showCheck: false,
        addressList: []
      };
    },
    mounted() {
      this.$nextTick(() => {
        this._initScroll(); // 初始化scroll
      });
    },
    activated() {
       this.initShippingAddressList();
    },
    components: {
      'v-header-title': headerWithTitle
    },
    methods: {
      // 检查地址是否可用
      initShippingAddressList() {
        let isDefault = '';
        getUserShippingAddressList(isDefault).then(data => {
          this.addressList = data;
          data.forEach((item) => {
            if (item.isDefault === DEFALUT_ADDRESS) {
              setSessionStorageItem('address', item);
            }
          })
          getBusinessSetting().then(response => { // 获取配送范围
            this.addressDistance();// 处理距离
          });
        });
      },
      addressDistance() {
        let self = this;
        let branch = getSessionStorageItem('currentBranch');
        let businessSetting = getSessionStorageItem('businessSetting');
        let OutBounds = 100000000;// 无坐标或超出范围使用该值方便排序
        if (branch.branchLongitude === '' || branch.branchLatitude === '') {
          self.addressList.forEach((currentValue, index) => {
            self.$set(self.addressList[index], 'distance', OutBounds); // 设置超出范围时的值
            self.$set(self.addressList[index], 'disable', true); // 设为不可选
          })
        } else {
          self.$amapLoad().then(() => {
            // 计算距离
            let lnglat = new AMap.LngLat(branch.branchLongitude, branch.branchLatitude)
            self.addressList.forEach((item, index) => {
              let distance
              if (item.longitude && item.latitude) {
                distance = lnglat.distance([item.longitude, item.latitude])
              } else {
                distance = OutBounds
              }
              // 处理是否超过配送距离
              distance = parseInt(distance);
              self.$set(self.addressList[index], 'distance', distance); // 设置超出范围时的值
              if (distance > (businessSetting.deliveryScope * 1000)) {
                self.$set(self.addressList[index], 'disable', true) // 设为不可选
              } else {
                self.$set(self.addressList[index], 'disable', false) // 设为不可选
              }
            });
            // 从小到大排序
            self.addressList.sort(function (item1, item2) {
              return item1.distance - item2.distance;
            })
          })
        }
      },
      _initScroll() {
        if (!this.addressBox) {
          this.addressBox = new BScroll(this.$refs.addressBox, {
            click: true
          });
        } else {
          this.addressBox.refresh()
        }
      },
      goAddAddress() {
        this.$router.push('/addressAdd');
      },
      editAddress(item) {
        let editAddress = setSessionStorageItem('editAddress', item);
        this.$router.push('/addressEdit');
      },
      deleteAddress(address) {
        let _this = this;
        MessageBox.confirm('确定删除此地址?', '提示').then(action => {
            deleteUserShippingAddress(address.id).then(res => {
              console.log('删除成功');
              this.addressList.forEach((item, index) => {
                if (item.id === address.id) {
                  _this.addressList.splice(index, 1);
                  if (item.isDefault === 'YES') {
                    _this.addressList[0].isDefault = 'YES';
                  }
                }
              })
            })
          }
        );
      },
      selectAddress(address) {
        if (address.disable) {
          return false
        }
        let _this = this;
        this.addressList.forEach((item, index) => {
          if (item.id === address.id) {
            item.isDefault = 'YES';
            _this.addressList.splice(index, 1);
            _this.addressList.unshift(item);
            let address = setSessionStorageItem('address', item);
            // this.$router.push('/orderDetail');// 外卖支付页,选中的新建本地存储address
          } else {
            item.isDefault = 'NO';
          }
        })
        this.$router.push('/order')
      }
    }
  }

</script>

<style lang="stylus">
  @import "../../common/stylus/mixin.styl";
  .address {
    .add-address {
      height: 1.61111rem;
      background: #fff;
      margin-top: 0.27778rem;
      border-1px: (rgb(216, 216, 216));
      .mint-cell {
        .icon-add {
          position: absolute;
          bottom: 0.52225rem;
          left: 0.38889rem;
          width: 0.55556rem;
          height: 0.55556rem;
          bg-image('add');
          background-size: 100% 100%;
        }
        .mint-cell-wrapper {
          height: 1.61111rem;
          padding-left: 0.38889rem;
          img {
            display: inline-block;
            width: 0.5rem;
            height: 0.5rem;
            background-size: 100% 100%;
          }
          .mint-cell-title {
            .mint-cell-text {
              margin-left: 0.8rem;
              font-size: 0.38889rem;
              color: #333;
            }
          }
        }
        .mint-cell-allow-right::after {
          width: 0.33333rem;
          height: 0.33333rem;
          right: 0.5rem;
        }
      }
    }
    .address-wrapper {
      margin-top: 0.27778rem;
      .disable {
        color: #999;
        opacity: 0.8;
      }
      .address-list {
        height: 2.22222rem;
        background: #fff;
        border-1px-top: (rgb(216, 216, 216));
        .list-content {
          padding: 0.55556rem 0.38889rem;
          font-size: 0.38889rem;
          color: #333;
          .icon-select {
            position: absolute;
            top: 0;
            left: 0;
            width: 0.55556rem;
            height: 0.55556rem;
            bg-image('select');
            background-size: 100% 100%;
          }
          .address-info {
            width: 7rem;
            display: inline-block;
            .address-detail {
              margin-bottom: 0.38889rem;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
            }
            .mobile {
              margin-left: 0.55556rem;
            }
          }
          .icon-modify {
            position: absolute;
            bottom: 0.80556rem;
            right: 1.5rem;
            width: 0.55556rem;
            height: 0.55556rem;
            bg-image('modify');
            background-size: 100% 100%;
          }
          .icon-delete {
            position: absolute;
            bottom: 0.80556rem;
            right: 0.38889rem;
            width: 0.55556rem;
            height: 0.55556rem;
            bg-image('del');
            background-size: 100% 100%;
          }
        }
      }
    }
  }
</style>
